class SessionController < ApplicationController

  def create
    if params["_method"] == "delete"
      destroy
      return
    end
    if params[:openid_url] && params[:openid_url] != ''
      open_id_authentication
    else
      password_authentication(params[:email], params[:password])
    end
  end
  
  def destroy
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "You have been logged out."
    redirect_back_or_default('/')
  end

  protected
  
    def password_authentication(email, password)
      self.current_user = User.authenticate(email, password)
      if logged_in?
        if params[:remember_me] == "1"
          self.current_user.remember_me
          cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
        end
        successful_login
      else
        failed_login('Invalid login or password')
      end
    end

    def open_id_authentication
      authenticate_with_open_id(params[:openid_url], :required => [ :nickname, :email ]) do |result, identity_url, registration|
        if result.successful?
          if !@user = User.find_by_identity_url(identity_url)
            @user = User.new(:identity_url => identity_url)
            assign_registration_attributes!(registration)
          end
          self.current_user = @user
          successful_login
        else
          failed_login(result.message || "Sorry could not log in with identity URL: #{identity_url}")
        end
      end
    end

    def assign_registration_attributes!(registration)
      { :login => 'nickname', :email => 'email' }.each do |model_attribute, registration_attribute|
        unless registration[registration_attribute].blank?
          @user.send("#{model_attribute}=", registration[registration_attribute])
        end
      end
      @user.save!
    end

  private
  
    def successful_login
      if current_user.application_errors.length == 0
        redirect_to :controller => 'home', :action =>'setup_instructions'
      else
        redirect_to :controller => 'home', :action =>'myerrors'
      end
    end

    def failed_login(message)
      flash[:error] = message
      redirect_to(:controller => 'home', :action => 'index', :login_error => message)
    end

end
